import wepy from 'wepy'
import { BASE_URL } from '@/util/config'
import dayjs from 'dayjs'
import {
  orderUpdate,
  wxPay,
  getUserInfo, 
  userInfo, 
  getPhoneNumber,
  decideMedic,
  updateTjOrder
} from '@/api/index'
// 授权
export class AuthMixin extends wepy.mixin {
  data = {
    nickName: '',
    phoneNumber: '',
    navigateUrl: '',
    canIUseGetUserProfile: false
  }
  onShow() {
    if (wx.getUserProfile) {
      this.canIUseGetUserProfile = true
    }
    this.$apply()
  }
  userInfo() {
    userInfo({
      openid: ''
    }).then(res => {
      this.nickName = res.nickName || ''
      this.phoneNumber = res.phoneNumber || ''
      this.$apply()
    })
  }
  SaveUser(res) {
    const params = {
      IV: res.iv,
      EncryptedData: res.encryptedData,
      openid: wx.getStorageSync('openid')
    }
    getUserInfo({
      ...params,
      session_key: ''
    }).then(res => {
      if (res.status == 0) {
        this.$parent.showToast('授权成功')
        this.userInfo()
      }
    })
  }
  methods = {
    // 微信信息授权
    getUserInfo() { // 老
      wepy.getUserInfo({ lang: 'zh_CN', withCredentials: true }).then(res => {
        if (res.errMsg === 'getUserInfo:ok') {
          this.SaveUser(res)
        } else {
          this.$parent.showToast('授权失败')
        }
      }).catch(err => {
        // 拒绝授权
        this.$parent.showToast('授权失败')
      })
    },
    getUserProfile(e) { // 新
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中
        success: (res) => {
          this.SaveUser(res)
        },
        fail: (res) => {
          this.$parent.showToast('授权失败')
        }
      })
    },
    // 手机号授权
    getPhoneNumber (e) {
      getPhoneNumber({
        iv: e.detail.iv,
        encryptedData: e.detail.encryptedData,
        openid: wx.getStorageSync('openid'),
        session_key: ''
      }).then(res => {
        if (res.status == 0) {
          this.downPhone()
        } else {
          this.$parent.showToast(res.msg)
        }
      })
    }
  }
}
// 支付
export class payAgainMixin extends wepy.mixin {
  data = {};
  // 判断体检团检绑定信息
  decideMedic() {
    this.paystatus = false
    if(this.ucard && this.form.groupid == 1) {
      decideMedic({
        openid: this.form.openid,
        order_no: this.form.order_no,
        ucard: this.ucard,
        prod_id: this.form.prodid
      }).then((res) => {
        if (res.status == '0') {
          this.paystatus = res.paystatus
          this.company = res.company
        }
        this.$apply()
      })
    }
  }
  // 根据支付方式判断是否需要授权订阅消息
  paystatusType() {
    if (this.paystatus) {
      this.orderUpdate()
    } else {
      let that = this
      let tmplIds = 'gDC2PpmfWRlzVW220tjFJ3G4H0hVXY7Fiqa0TXxprIA'
      wx.requestSubscribeMessage({   // 调起消息订阅界面
        tmplIds: [tmplIds],
        success (res) {
          if (res[tmplIds] == 'accept') {
            that.orderUpdate()
          }
        },
        fail (res) {
          console.log(res, 'file')
        }
      })
    }
  }
  // 更新信息
  orderUpdate() {
    orderUpdate(this.form).then((res) => {
      if (res.status == '0') {
        if (this.paystatus) {
          this.updateTjOrder()
        } else {
          this.wxPay()
        }
      } else {
        this.$parent.showToast(res.msg)
      }
    })
  }
  // 已经支付团体免支付
  updateTjOrder() {
    updateTjOrder({
      openid: this.form.openid,
      order_no: this.form.order_no,
      prodid: this.form.prodid,
      sell_price: this.form.sell_price,
      ucard: this.ucard
    }).then((res) => {
      if (res.status == '0') {
        wx.redirectTo({
          url: `../placeOrder/success?sell_price=${this.form.sell_price}`
        })
      } else {
        this.$parent.showToast(res.msg)
      }
    })
  }
  // 支付
  wxPay(){
    wxPay({
      openid: this.form.openid,
      order_no: this.form.order_no,
      prodid: this.form.prodid,
      sell_price: this.form.sell_price
    }).then((res) => {
      if (res.status == '0') {
        let Paymodel = res.data
        this.doPay(Paymodel)
      } else {
        this.$parent.showToast(res.msg)
      }
    })
  }
  doPay(payModel) {
    wepy
      .requestPayment(payModel)
      .then((res) => {
        wx.redirectTo({
          url: `../placeOrder/success?sell_price=${this.form.sell_price}`
        })
      })
      .catch((res) => {
        // 取消支付下单失败
        this.$parent.showToast('支付失败')
      })
  }
}
// 倒计时
export class CountDown extends wepy.mixin {
  data = {
    countTag: -1,
    day: '',
    hour: '',
    minute: '',
    second: ''
  };
  timeCount(info) {
    console.log('1次')
    this.hour = ''
    this.minute = ''
    this.second = ''
    let t1 = dayjs(info.StartTime)
    let t2 = dayjs(info.EndTime)
    let s = Math.floor(t2.diff(t1) / 1000)
    if (s > 0) {
      this.formatTime(s)
      this.AddCountdown()
    }
    clearInterval(this.countTag)
    this.countTag = setInterval(() => {
      s--
      if (s >= 0) {
        this.formatTime(s)
        this.AddCountdown()
        this.$apply()
      } else {
        this.EndCountdown()
        this.clearCount()
      }
    }, 1000)
  }
  formatTime(s) {
    if (this.showDay) {
      // 显示天数
      this.day = this.padNum(Math.floor(s / (60 * 60 * 24)))
      this.hour = this.padNum(Math.floor((s / (60 * 60)) % 24))
    } else {
      this.hour = this.padNum(parseInt(s / (60 * 60)))
    }
    this.minute = this.padNum(parseInt(s / 60 % 60))
    this.second = this.padNum(parseInt(s % 60))
  }
  padNum(v) {
    return v < 10 ? `0${v}` : `${v}`
  }
  clearCount() {
    this.hour = ''
    this.minute = ''
    this.second = ''
    this.timeTxt = ''
    clearInterval(this.countTag)
    this.countTag = -1
  }
}
